<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Page extends BIT_Controller {

	/**
	 * Index Page for this controller.
	 *
	 * Maps to the following URL
	 * 		http://example.com/index.php/welcome
	 *	- or -  
	 * 		http://example.com/index.php/welcome/index
	 *	- or -
	 * Since this controller is set as the default controller in 
	 * config/routes.php, it's displayed at http://example.com/
	 *
	 * So any other public methods not prefixed with an underscore will
	 * map to /index.php/welcome/<method_name>
	 * @see http://codeigniter.com/user_guide/general/urls.html
	 */
	public function __construct()
	{
		parent::__construct();
		$this->header_views = array('common/header');
		$this->footer_views = array('common/footer');
	}

	public function index()
	{
		$this->view_data["product_html"] = $this->getProductBoxHtml( $this->produkter->getStartpageProducts( 3 ) );
		$this->view_data['news'] = $this->news->getLatestNews(4);

		$this->v('pages/home');
	}

	public function sortiment(){
		$this->view_data["product_html"] = $this->getProductBoxHtml( $this->produkter->getProductPageProducts() );
		$this->v('pages/sortiment');
	}

	public function recept(){
		$this->view_data['recipes'] = $this->recept->getRecipeList();
		$this->v('pages/recept');
	}

	public function about(){
		$this->view_data['widgets'] = array(
			0 => $this->load->view('widgets/workwithus.php', null, TRUE),
			1 => $this->load->view('widgets/newsletter.php', null, TRUE)
		);

		// Get html content
		$pages = $this->db->get_where('boxdata', array('boxname'=>'omfiskkillenboxkanni'), 1)->result();
		$this->view_data['page'] = $pages[0];

		// Areas of delivery
		$this->view_data['areas'] = $this->db->order_by('namn','ASC')->get('omraden')->result();

		// Show page
		$this->v('pages/about');
	}

	public function product( $id ){
		
		// Get bestselling widget and data
		$widget_data = array('bestsellers_html' => $this->getProductBoxHtml( $this->produkter->getBestSellers() ));
		$this->view_data['widgets'] = array($this->load->view('widgets/bestsellers', $widget_data, TRUE));

		// Get product info
		$id = intval( $id );
		$product = $this->produkter->getProduct( $id );
		$this->view_data['product'] = $product;

		// Get 2 most popular recipes
		$this->view_data['relatedRecipes'] = $this->recept->getProductRelatedRecipes( $product->typ, 2 );

		// Display page
		$this->v('pages/produkt');
	}

	public function contact(){
		$mail_sent = false;

		# Loading configuration file mail_config.php
		$this->config->load('mail_config',true);

        if ($this->input->post('q'))
        {
        	$this->load->helper(array('form', 'url'));
			$this->load->library('form_validation');
			$form_rules = array(
				array(
					'field' => 'from',
					'label' => 'epost',
					'rules' => 'trim|valid_email|required'
				),
				array(
					'field' => 'name',
					'label' => 'namn',
					'rules' => 'min_length[3]|required'
				),
				array(
					'field' => 'subject',
					'label' => 'ämne',
					'rules' => 'min_length[3]|required'
				),
				array(
					'field' => 'message',
					'label' => 'meddelande',
					'rules' => 'min_length[20]|required'
				)
			);
			$this->form_validation->set_message('required', 'Du måste fylla i %sfältet');
			$this->form_validation->set_message('min_length', '%s får inte vara kortare än %s tecken');
			$this->form_validation->set_message('valid_email', 'Epostadressen är ogiltig');

			$this->form_validation->set_rules($form_rules);
			
			if($this->form_validation->run() == TRUE)
			{
	            # Loading email library of Codeigniter
	            $this->load->library('email');
	            # Setting email address and name of the person sending the email
	            $this->email->from($this->input->post('from'),$this->input->post('name'));
	            # Setting email address of the recipient
	            $this->email->to($this->config->item('to','mail_config'));
	            # Setting email subject
	            $this->email->subject($this->input->post('subject'));
	            # Setting email message body
	            $this->email->message($this->input->post('message',true));
	            # If mail sending successful
	            if ($this->email->send())
	            {
	                # If $mail_sent = true; it will show a success message.
	                $mail_sent = true;
	            }
	        }
        }
        # Get contact form html
        # $this->view_data['html'] = $this->pages->getPageBySlug('kontakt');

        # Showing Contact Form
        $this->view_data['mail_sent'] = $mail_sent;
        $this->view_data['mailaddress'] = $this->config->item('to','mail_config');
        $this->v('pages/kontakt');
	}

	public function newsletter_signup(){

		if ($this->input->post('sign_up_email'))
        {
        	$this->load->helper(array('form', 'url'));
			$this->load->library('form_validation');
			$form_rules = array(
				array(
					'field' => 'sign_up_email',
					'label' => 'epost',
					'rules' => 'trim|valid_email|required'
				)
			);
			$this->form_validation->set_message('required', 'Du måste fylla i %sfältet');
			$this->form_validation->set_message('valid_email', 'Epostadressen är ogiltig');

			$this->form_validation->set_rules($form_rules);
			
			if($this->form_validation->run() == TRUE)
			{
				# Update database with email address
				$added = $this->db->insert('mail_adresser', array('mail' => $this->input->post('sign_up_email')));

				/*		Send TY mail?

	            # Loading email library of Codeigniter
	            $this->load->library('email');
	            # Setting email address and name of the person sending the email
	            $this->email->from($this->input->post('from'),$this->input->post('name'));
	            # Setting email address of the recipient
	            $this->email->to($this->config->item('to','mail_config'));
	            # Setting email subject
	            $this->email->subject($this->input->post('subject'));
	            # Setting email message body
	            $this->email->message($this->input->post('message',true));
	            # If mail sending successful
	            if ($this->email->send())
	            {
	                # If $mail_sent = true; it will show a success message.
	                $mail_sent = true;
	            }
				*/
	        }
	        else {
	        	$added = false;
	        }
        }
        # Get contact form html
        # $this->view_data['html'] = $this->pages->getPageBySlug('kontakt');

        # Showing Contact Form
        $this->view_data['added'] = $added;
        $this->view_data['mailaddress'] = $this->config->item('to','mail_config');
        $this->v('pages/newsletter_signup');
	}

	public function getProductBoxHtml( $product ) {

		$template = 'common/product';
		
		// list of products?
		if(is_array($product)) {
			$html = "";
			foreach($product as $p){
				$html .= $this->load->view($template, array('product'=>$p), TRUE);
			}
			return $html;
		}
		// Single product?
		else {
			return $this->load->view( $template, array('product'=>$product), TRUE);
		}
	}

	public function create_unique_slug($string, $table)
	{
	    $slug = url_title($string);
	    $slug = strtolower($slug);
	    $i = 0;
	    $params = array ();
	    $params['slug'] = $slug;
	    if ($this->input->post('id')) {
	        $params['id !='] = $this->input->post('id');
	    }
	    
	    while ($this->db->where($params)->get($table)->num_rows()) {
	        if (!preg_match ('/-{1}[0-9]+$/', $slug )) {
	            $slug .= '-' . ++$i;
	        } else {
	            $slug = preg_replace ('/[0-9]+$/', ++$i, $slug );
	        }
	        $params ['slug'] = $slug;
	        }
	    return $slug;
	} 

	public function fix_slugs() {
		$products = $this->produkter->getProducts();
		
		foreach($products as $p){
			$p->slug = $this->create_unique_slug($p->namn, "produkter");
			$this->products->saveProduct($p);
		}
	}
}